package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.Student;
import com.example.demo.mapper.StudentMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author lai
 * @data 2021/11/16
 * @apiNote
 */
@RestController
@RequestMapping("/stu")
public class StudentController {

    @Resource
    StudentMapper studentMapper;

    //插入数据

    @PostMapping
    public Result<?> save(@RequestBody Student student){
        Result result;
        try {
            studentMapper.insert(student);
            result = Result.success(student.getId());
        }catch (Exception e){
            result = Result.fail();
        }
        return result;
    }

    /**
     * 判断是否已有用户
     *
     *
     * @return*/
    @GetMapping("/findSame/{name}"+"&"+"{password}")
    public Result<?> findSame(@PathVariable String name, @PathVariable String password){
        Result result = null;
        List<Student> students = studentMapper.selectList(null);
        for (int i = 0; i < students.size(); i++){
            if (name.equals(students.get(i).getName()) && password.equals(students.get(i).getPassword())) {
                result = Result.success(students.get(i));
                break;
            }
            else if (i == students.size()-1){
                result = Result.fail();
            }
        }
        return result;
    }

    //更新表

    @PutMapping
    public Result<?> updata(@RequestBody Student student){
        Result result;
        try {
            Student test = new Student();
            test.setId(student.getId());
            test = student;
            studentMapper.updateById(test);
            result = Result.success();
        }catch (Exception e){
            result = Result.fail();
        }
        return result;
    }

    // 根据id查询

    @GetMapping("/{id}")
    public Result<?> find(@PathVariable Integer id){
        Student res = studentMapper.selectById(id);
        return Result.success(res);
    }
    // 查询全部

    @GetMapping()
    public Result<?> findAll(){
        List<Student> res = studentMapper.selectList(null);
        return Result.success(res);
    }

    // 根据id删除

    @DeleteMapping("/{id}")
    public Result<?> delte(@PathVariable Integer id){
        studentMapper.deleteById(id);
        return Result.success();
    }

    @GetMapping("/class")
    public Result<?> byClass(@RequestBody Integer classId){
        List<Student> res = studentMapper.selectByClassId(classId);
        return Result.success(res);
    }

    @PostMapping("/"+"{id}"+"&"+"{portrait}")
    public void insertPortrait(@PathVariable Integer id,@PathVariable String portrait){
        portrait = portrait.replaceAll("，","/").replace("。","http://localhost:9090");
        Student student = new Student();
        student.setId(id);
        student.setPortrait(portrait);
        studentMapper.updateById(student);
    }

}
